#include "BlockQueue.hpp"
#include "Task.hpp"
#include <ctime>


void* consumer(void* args)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task>*>(args);
    while(true)
    {
        usleep(10);
        // 消费者消费数据
        Task task = bq->pop();
        
        // 加工数据
        task.run();
        cout << "处理了一个任务: " << task.GetResult() << "thread id: " << pthread_self() << endl;
        //sleep(2);
    }
}


void* productor(void* args)
{
    int len = opsum.size();
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task>*>(args);
    while(true)
    {
        sleep(2);
        // 生产者获取数据
        int x = rand() % 10 + 1;  // [1,10]
        int y = rand() % 10 + 1;  // [1,10]
        char op = opsum[rand() % len];
        Task task(x, y, op);

        // 生产任务
        bq->push(task);
        cout << "生产了一个任务: " << task.GetTask() << endl; 
        
    }
}


int main()
{
    srand(time(nullptr));
    BlockQueue<Task> *bq = new BlockQueue<Task>;
    pthread_t c[3], p[5];
    for(int i = 0; i < 3; i++)
    {
        pthread_create(c + i, nullptr, consumer, bq);
    }
    for(int i = 0; i < 5; i++)
    {
        pthread_create(p + i, nullptr, productor, bq);
    }
    
    for(int i = 0; i < 3; i++)
    {
        pthread_join(c[i], nullptr);
    }
    for(int i = 0; i < 5; i++)
    {
        pthread_join(p[i], nullptr);
    }
    
    delete bq;
    return 0;
}
